﻿using StarPizza.Model.BaseModel;
using StarPizza.Model.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StarPizza.ViewModel.Core
{
    class PizzaComposer : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event Action ToppingsChanged;

        IIngredientResource ingredientResource;
        ToppingLister toppingLister;

        public ToppingLister ToppingLister { get { return toppingLister; } }
        public ObservableCollection<ToppingVM> ChosenToppingVMs { get; set; }
        public ToppingVM ChosenSelectedToppingVM { get; set; }
        public int SumToppingPrice
        {
            get { return ChosenToppingVMs.Sum(topping => topping.Price); }
        }
        public PizzaComposer(IIngredientResource ingredientResource, ToppingLister toppingLister)
        {
            this.ingredientResource = ingredientResource;
            this.toppingLister = toppingLister;
            ChosenToppingVMs = new ObservableCollection<ToppingVM>();
            toppingLister.IngredientVMChosen += ChooseToppingVM;
        }
        public void ClearChosenToppingVMs()
        {
            ChosenToppingVMs.Clear();
            HandleToppingsChanged();
        }
        private void HandleToppingsChanged()
        {
            OnPropertyChanged("SumToppingPrice");
            if (ToppingsChanged != null)
                ToppingsChanged();
        }
        private void ChooseToppingVM(ToppingVM toppingVM)
        {
            if (!ChosenToppingVMs.Contains(toppingVM))
            {
                ChosenToppingVMs.Add(toppingVM);
                HandleToppingsChanged();
            }
        }
        public void CancelChosenSelectedToppingVM()
        {
            ChosenToppingVMs.Remove(ChosenSelectedToppingVM);
            HandleToppingsChanged();
        }
        public PizzaTemplate ProvidePizzaTemplate(string name)
        {
            PizzaTemplate template = new PizzaTemplate
            {
                Name = name
            };
            foreach (var toppingVM in ChosenToppingVMs)
            {
                template.PizzaComposition.Add(
                    new PizzaComposition
                    {
                        Topping = toppingVM.WrappedTopping
                    });
            }
            return template;
        }
    }
}
